<?php

namespace App\Http\Controllers\admin;

use Illuminate\Http\Request;

use App\Http\Controllers\common\MyAgentController;

use App\Http\Controllers\Controller;

use DB;
class AreaController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    //区域列表方法
    public function getIndex(Request $request)
    {
        $get = array();
        $get['area'] = $request->input('area','');
        $agentId = $request->cookie('agentId');
        $get['ag'] = $request->input('ag',$agentId);
        //查询父级代理商path
        $path = DB::table('sa_agent') -> select('path') -> where(['id'=>$agentId]) -> first();
        $len = substr_count($path['path'],',');
        $agent = MyAgentController::allAgent($agentId);
        foreach ($agent as $k=>$v){
            $agent[$k]['agent_name'] = str_repeat('--',substr_count($v['path'],',')-$len)."<img src='/admin/images/company.png'>&nbsp;&nbsp;".$v['agent_name'];
        }
        //查询代理商下的所有区域
        $data = DB::table('sa_area as a')
                    -> where(['a.a_agent_id'=>$get['ag']])
                    -> select('a.a_id','a.a_name')
                    -> where('a.a_name','like','%'.$get['area'].'%')
                    -> paginate(1);
        $info = $data->all();
        foreach ($info as $k=>$v){
            //联查关系表和建筑表, 拿出mma_uid
            $temp = DB::table('sa_member_manager_area') -> select('mma_uid') -> where(['mma_a_id'=>$v['a_id'],'mma_b_id'=> 0,'mma_r_id'=> 0]) -> first();
            $info[$k]['mma_uid'] = $temp['mma_uid'];
        }
        foreach ($info as $k=>$v){
            $userStr = '';
            $idArr = explode(',',$v['mma_uid']);
            foreach ($idArr as $val){
                //查询用户表
                $userArr = DB::table('sa_member') -> select('username') -> where(['uid'=>$val]) -> first();
                $userStr .= $userArr['username'].',';
            }
            $info[$k]['mma_username'] = substr($userStr,0,-1);
        }
        return view('admin.area.index',['agent'=>$agent,'data'=>$data,'info'=>$info,'request'=>$request->all(),'get'=>$get]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    //添加区域方法
    public function getCreate()
    {
        return view('admin.area.create');
    }

    //添加区域处理方法
    public function postCreate(Request $request){
        //获取数据
        $area_name = trim($request ->input('area_name'));
        if($request ->input('manage')){
            $manage = array_unique($request ->input('manage'));
        }else{
            $manage = [];
        }
        // $agentID = session('agentId');
        $agentID = $request->cookie('agentId');
        //将区域信息插入区域表
        if($agentID){
            //用户是否登录
            $a_data = array(
                'a_name' => $area_name,
                'a_agent_id' => $agentID
            );
            $a_id = DB::table('sa_area') -> insertGetId($a_data);
            //将用户信息插入关系表
            if($a_id){
                //区域信息插入成功
                foreach ($manage as $k=>$v){
                    //查询用户表
                    $row = DB::table('sa_member') -> where(['username'=>$v]) -> first();
                    $manage[$k] = $row['uid'];
                }
                $mma_uid = implode(',',$manage);
                $mma_data = array(
                    'mma_uid'=>$mma_uid,
                    'mma_a_id'=>$a_id
                );
                $mma_id = DB::table('sa_member_manager_area') -> insertGetId($mma_data);
                if($mma_id){
                    //关系表插入成功
                    $msg['status'] = '1';
                    $msg['msg'] = '操作成功';
                }else{
                    //关系表插入失败
                    $msg['status'] = '-2';
                    $msg['msg'] = '关系表插入失败';
                }
            }else{
                //区域表插入失败
                $msg['status'] = '-1';
                $msg['msg'] = '区域表插入失败';
            }
        }else{
            $msg['status'] = '-3';
            $msg['msg'] = '请登录后添加';
        }
        echo json_encode($msg);
    }

    //编辑区域页面
    public function getEdit(Request $request){
        $a_id = $request -> input('a_id');
        //联查区域表和关系表
        $data = DB::table('sa_area as a')
            -> where(['a.a_id'=>$a_id])
            -> select('a.a_id','a.a_name')
            -> first();
        //联查关系表和建筑表, 拿出mma_uid
        $temp = DB::table('sa_member_manager_area') -> select('mma_uid') -> where(['mma_a_id'=>$a_id,'mma_b_id'=> 0,'mma_r_id'=> 0]) -> first();
        if($temp){
            $data['mma_uid'] = $temp['mma_uid'];
        }else{
            $data['mma_uid'] = '';
        }
        $userArr = [];
        $idArr = explode(',',$data['mma_uid']);
        foreach ($idArr as $val){
            //查询用户表
            $user = DB::table('sa_member') -> select('username') -> where(['uid'=>$val]) -> first();
            if($user['username'] != null){
                $userArr[] = $user['username'];
            }
        }
        $data['mma_username'] = $userArr;
        return view('admin.area.edit',['data'=>$data]);
    }

    //编辑区域处理方法
    public function postEdit(Request $request){
        //获取数据
        $a_id = $request ->input('a_id');
        $area_name = trim($request ->input('area_name'));
        if($request ->input('manage')){
            $manage = array_unique($request ->input('manage'));
        }else{
            $manage = [];
        }
        //修改区域表
        $area_data = array(
          'a_name'=>$area_name
        );
        $row1 = DB::table('sa_area') -> where(['a_id'=>$a_id]) -> update($area_data);
        //修改关系表
        foreach ($manage as $k=>$v){
            //查询用户表
            $row = DB::table('sa_member') -> where(['username'=>$v]) -> first();
            $manage[$k] = $row['uid'];
        }
        $mma_uid = implode(',',$manage);
        $mma_data = array(
            'mma_a_id'=>$a_id,
            'mma_uid'=>$mma_uid
        );
        //查询关系表
        $res = DB::table('sa_member_manager_area') -> where(['mma_a_id'=>$a_id,'mma_b_id'=>0,'mma_r_id'=>0]) -> first();
        if($res){
            $row2 = DB::table('sa_member_manager_area') -> where(['mma_a_id'=>$a_id,'mma_b_id'=>0,'mma_r_id'=>0]) -> update($mma_data);
        }else{
            $row2 = DB::table('sa_member_manager_area') -> where(['mma_a_id'=>$a_id,'mma_b_id'=>0,'mma_r_id'=>0]) -> insertGetId($mma_data);
        }
        if($row1){
            $arr['status1'] = '1';
        }else{
            $arr['status1'] = '-1';
            $arr['msg1'] = '区域表未操作';
        }
        if($row2){
            $arr['status2'] = '1';
        }else{
            $arr['status2'] = '-1';
            $arr['msg2'] = '关系表未操作';
        }
        echo json_encode($arr);
    }

    //验证管理员是否存在
    public function postExists(Request $request){
        //获取数据
        $data = array();
        $manage = $request ->input('manage');
        //查询用户表,判断用户是否存在
        $row = DB::table('sa_member') -> where(['username'=>$manage]) -> first();
        if($row){
            $data['status'] = '1';
        }else{
            $data['status'] = '-1';
            $data['msg'] = '该用户不存在';
        }
//        dd($data);
        echo json_encode($data);
    }
    public function getDelete(Request $request)
    {
        $id = base64_decode($request -> get('id'));
        $count = 0;
        $count += DB::table('sa_smoke_detector') -> where('a_id','=',$id) -> count();
        $count += DB::table('sa_electric_detector') -> where('a_id','=',$id) -> count();
        $count += DB::table('sa_infrared_detector') -> where('a_id','=',$id) -> count();
        $count += DB::table('sa_gas_detector') -> where('a_id','=',$id) -> count();
        $count += DB::table('sa_call_help_detector') -> where('a_id','=',$id) -> count();
        if($count != 0){
            return back() -> withInput() -> with('error','该区域下有'.$count.'个设备，请移除后再进行删除!');
        }else{
            DB::table('sa_room') -> where('r_a_id','=',$id) -> delete();
            DB::table('sa_building') -> where('b_a_id','=',$id) -> delete();
            DB::table('sa_member_manager_area') -> where('mma_a_id','=',$id) -> delete();
            DB::table('sa_area') -> where('a_id','=',$id) -> delete();
            return redirect('/admin/area/index') -> with('success','删除成功');
        }
    }
}
